home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Shareware Grab Bag
/
Shareware Grab Bag.iso
/
090
/
cmln0986.arc
/
EXPON1.LTG
< prev
next >
Wrap
Text File
|
1980-02-17
|
3KB
|
65 lines
1: {======================================================================
2:
3: POWER.PAS
4:
5: Routine to calulate x^n
6:
7: Usage: Result : real; (*x^n*)
8: x : real; (*base*)
9: n : real; (*exponent*)
10:
11: Result := Power( x, n );
12:
13: Method: If the exponent is not integral, the result is
14: calculated using the log-exponential method. If
15: n has no fractional part, the result is calculated
16: by the recursion method. A call with base = 0 will
17: always return 0.
18:
19: Errors: The only error condition is a negative base with a
20: non-integral exponent, which causes an error in the
21: log routine. POWER.PAS assumes that the log routine
22: will handle the error. If the commented-out code on
23: lines 55 and 56 are uncommented, Power will call a
24: user-supplied routine, Error, with the single argument
25: LOG_ARG.
26:
27: ======================================================================}
28:
29: function Power( x : real; n : real ) : real;
30:
31: Const
32: LOG_ARG = 1; {for error trapping}
33:
34: {local function to do recursion}
35:
36: function pwr( n : integer ) : real;
37:
38: begin {pwr}
39: if n = 1 then {case 1 of rule}
40: pwr := x {--end recursion}
41: else if odd( n ) then {case 2 of rule}
42: pwr := sqr( pwr( n div 2 ) ) * x {--do recursion}
43: else {case 3 of rule}
44: pwr := sqr( pwr( n div 2 ) ); {--do recursion}
45: end; {pwr}
46:
47: begin {Power}
48:
49: if x = 0 then {pick off the easy}
50: Power := 0 {--cases of x = 0}
51: else if n = 0 then {--and n = 0 first}
52: Power := 1
53: else if frac( n ) <> 0 then {non-integral exponent}
54: begin
55: (* if x < 0 then {illegal log argument?}è 56: Error(LOG_ARG); *) {yes - trap it}
57: Power := exp( n * ln ( x ) )
58: end
59: else if n < 0 then {negative integral exponent}
60: Power := 1/pwr( -trunc( n ) ) {--x^(-n) becomes 1/x^n}
61: else {positive integral exponent}
62: Power := pwr( trunc( n ) ); {--calculate it recursively}
63:
64: end; {Power}